<?php


namespace App\Http\Controllers\Frontend;



use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Business\Models\Video;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Exception;



class AliyunController extends FrontendController
{


    public function callback(Request $request)
    {


        $data = $request->input();

        if ($data['Status'] == 'success') {
            switch ($data['EventType']) {
                case 'SnapshotComplete':
                    $this->changeThumb($data);
                    break;

                case 'FileUploadComplete':
                    $this->insertUrl($data);
                    break;
                case  'ProduceMediaComplete':
                    break;
                default :
                    echo '回调事件类型不合法';
                    exit;
            }
        }

        return 'success';

    }

    /**
     * @param $data
     * @return JsonResponse
     */
    public function changeThumb($data)
    {

        if (!isset($data['VideoId'])) {
            return $this->error(__('参数错误'));
        }
        $video = Video::query()->where('aliyun_video_id', $data['VideoId'])->first();
        if (isset($data['CoverUrl']) && empty($video['thumb'])) {
            $coverUrl = substr($data['CoverUrl'], 0, stripos($data['CoverUrl'], "?")?:strlen($data['CoverUrl']));
            $video->update(['thumb' => $coverUrl]);

        }

        return $this->success(__('successful'));

    }


    /**
     * @param $data
     * @return JsonResponse
     */
    public function insertUrl($data)
    {

        if (!empty($data['FileUrl'])) {
            $video = Video::query()->where('aliyun_video_id', $data['VideoId'])->firstOrFail();
            $video->update(['url' => $data['FileUrl']]);
        }
        return $this->success(__('successful'));

    }



}
